from flask_app import app
from flask import Flask, request, jsonify
from connect.mqtt_client_singleton import mqtt_client
import requests
from dto import *


@app.route('/create_mq_user', methods=['POST'])
def create_auth_user():
    try:
        request_data = request.get_json()
        create_auth_user_request = CreateAuthUserRequest(
            user_id=request_data.get('user_id'),
            password=request_data.get('password')
        )

        data = {
            "user_id": create_auth_user_request.user_id,
            "password": create_auth_user_request.password
        }

        # Perform the equivalent logic in Python for creating an authentication user
        response = requests.post(
            "http://119.91.228.85:18083/api/v5/authentication/password_based%3Abuilt_in_database/users", json=data)
        response_data = response.json()

        create_auth_user_reply = CreateAuthUserReply(
            is_superuser=response_data.get('is_superuser', False),
            user_id=response_data.get('user_id', '')
        )

        return jsonify({
            "is_superuser": create_auth_user_reply.is_superuser,
            "user_id": create_auth_user_reply.user_id
        }), 200

    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/delete_mq_user', methods=['POST'])
def delete_auth_user():
    try:
        client_id = request.json.get('client_id')

        # Perform the equivalent logic in Python for deleting an authentication user
        response = requests.delete(
            "http://119.91.228.85:18083/api/v5/authentication/password_based%3Abuilt_in_database/users/" + client_id)

        if response.text:
            return jsonify({"message": "User deleted successfully"}), 200
        else:
            return jsonify({"error": "Client not found"}), 404

    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/subscribe_topic', methods=['POST'])
def subscribe_topic():
    try:
        client_id = request.json.get('client_id')
        topic = request.json.get('topic')

        mqtt_client.subscribe(topic, client_id)

        return jsonify({"message": f"Subscribed {client_id} to {topic}"}), 200

    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/unsubscribe_topic', methods=['POST'])
def unsubscribe_topic():
    try:
        client_id = request.json.get('client_id')
        topic = request.json.get('topic')

        mqtt_client.unsubscribe(topic, client_id)

        return jsonify({"message": f"Unsubscribed {client_id} from {topic}"}), 200

    except Exception as e:
        return jsonify({"error": str(e)}), 500
